package com.ly.blog_article.controller;


import com.ly.blog_article.entity.IssueEntity;
import com.ly.blog_article.feign.ThirdService;
import com.ly.blog_article.feign.UserService;
import com.ly.blog_article.service.InfoService;
import com.ly.blog_article.service.IssueService;
import com.ly.blog_common.constant.Constant;
import com.ly.blog_common.entity.InfoEntity;
import com.ly.blog_common.entity.MsgEntity;
import com.ly.blog_common.entity.SysUserEntity;
import com.ly.blog_common.entity.mq.EmailMqInfo;
import com.ly.blog_common.entity.mq.MqMsgEntity;
import com.ly.blog_common.response.BlogResponseStatus;
import com.ly.blog_common.security.SecurityUtils;
import com.ly.blog_common.utils.DateUtils;
import com.ly.blog_common.utils.PageUtils;
import com.ly.blog_common.utils.R;
import com.ly.blog_common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;




/**
 * 
 *
 * @author liyang
 *
 * @date 2021-07-30 10:37:42
 */
@Slf4j
@RestController
@RequestMapping("article/issue")
public class IssueController {
    @Autowired
    private IssueService issueService;
    @Autowired
    private UserService userService;
    @Autowired
    private InfoService infoService;
    @Autowired
    private ThirdService thirdService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = issueService.queryPage(params);

        return R.ok().put("page", page);
    }

    @RequestMapping("show/list")
    public R showList(@RequestParam Map<String, Object> params){
        PageUtils page = issueService.queryShowPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
		IssueEntity issue = issueService.getById(id);

        return R.ok().put("issue", issue);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody IssueEntity issue){
        String userId = SecurityUtils.getUserId();
        if(StringUtils.isBlank(issue.getWord())){
            return R.error(BlogResponseStatus.ISSUE_WORD_EMPTY);
        }
        if(userId == null){
            return R.error(BlogResponseStatus.USER_NO_LOGIN);
        }
        issue.setCreateBy(userId);
        issue.setCreateTime(new Date());
        issue.setLastUpdateBy(userId);
        issue.setLastUpdateTime(new Date());
		issueService.save(issue);

		//增加消息记录 - 评论、留言后将发送给对应用户
        MsgEntity msgEntity = new MsgEntity();
        msgEntity.setType(2);
        msgEntity.setFromId(Integer.parseInt(userId));
        InfoEntity infoEntity = infoService.getById(issue.getContentId());
        Integer articleUserId = infoEntity == null?Constant.SUPER_ADMIN:Integer.parseInt(infoEntity.getCreateBy());
        msgEntity.setToId(articleUserId); //文章的发起者

        msgEntity.setContent(issue.getWord());
        userService.saveMsg(msgEntity);


        //推送到作者邮箱 - 留言退给站主
        //找到作者邮箱
        SysUserEntity sysUserEntity = userService.infoShow(articleUserId.longValue());
        if(sysUserEntity == null){
            sysUserEntity = userService.infoShow(Integer.valueOf(Constant.SUPER_ADMIN).longValue());
        }

        MqMsgEntity<EmailMqInfo> mqMsgEntity = new MqMsgEntity<>();

        Map<String,String> param = new HashMap<>();
        param.put("userAlias",SecurityUtils.getUser().getAlias());
        param.put("title",infoEntity==null?"留言板":infoEntity.getTitle());
        param.put("issueTime",DateUtils.format(issue.getCreateTime(),DateUtils.DATE_TIME_PATTERN));
        EmailMqInfo emailMqInfo = new EmailMqInfo(param,EmailMqInfo.Type.NOTICE.getTypeNumber(),sysUserEntity.getEmail());
        mqMsgEntity.setMsg(emailMqInfo);
        mqMsgEntity.setType(MqMsgEntity.Type.EMAIL);
        if(thirdService.send(mqMsgEntity).getCode() != 0){
            log.error("【评论发送邮件】 - 发送邮件失败 - 评论信息：{}",issue.getWord());
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody IssueEntity issue) {
        issue.setLastUpdateBy(SecurityUtils.getUserId());
        issue.setLastUpdateTime(new Date());
        issueService.updateById(issue);

        return R.ok();
    }

    /**
     * 维护赞数量
     * @param issue
     * @return
     */
    @RequestMapping("/update/zan/add")
    public R updateZanAdd(@RequestBody IssueEntity issue, HttpServletRequest request){
        String userId = SecurityUtils.getUserId();
        if(userId == null){
            return R.error(BlogResponseStatus.USER_NO_LOGIN);
        }
        issue = issueService.getById(issue.getId());
        issue.setZan(issue.getZan()!=null && issue.getZan()> 0?issue.getZan() + 1 :1);
		issueService.updateById(issue);

		//追加记录
        issue.setCreateBy(userId);
        issue.setLastUpdateBy(userId);
        issueService.addRecord(issue);

        return R.ok();
    }

    /**
     * 维护赞数量
     * @param issue
     * @return
     */
    @RequestMapping("/update/zan/cancel")
    public R updateZanCancel(@RequestBody IssueEntity issue, HttpServletRequest request){
        String userId = SecurityUtils.getUserId();
        if(userId == null){
            return R.error(BlogResponseStatus.USER_NO_LOGIN);
        }
        issue = issueService.getById(issue.getId());
        issue.setZan(issue.getZan()!=null && issue.getZan()> 0?issue.getZan() - 1 :0);
		issueService.updateById(issue);

		//追加记录
        issue.setLastUpdateBy(userId);
        issueService.cancelRecord(issue);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
		issueService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
